<template>
  <el-card>
    <!-- 标题 -->
    <template #header>
      <h2>账户列表</h2>
    </template>
    <!-- 表格 -->
    <div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        size="mini"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="account" label="账号"> </el-table-column>
        <el-table-column prop="userGroup" label="用户组"> </el-table-column>
        <el-table-column label="创建时间">
          <template v-slot="{ row }">
            <p>{{ row.ctime | formateDate }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="primary" @click="edit(row)" size="mini"
              >编辑</el-button
            >
            <el-button type="danger" @click="del(row.id)" size="mini"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[1, 5, 10, 15]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 按钮 -->
      <el-button size="mini" type="danger" @click="delMore">批量删除</el-button>
      <el-button size="mini" type="primary" @click="toggleSelection()"
        >取消选择</el-button
      >
    </div>
    <!-- 编辑功能面板 -->
    <el-dialog title="编辑用户" :visible.sync="dialogVisible" width="30%">
      <div>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="60px"
          class="demo-ruleForm"
          size="mini"
        >
          <el-form-item label="账号" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="用户组">
            <el-select
              v-model="ruleForm.userGroup"
              clearable
              placeholder="请选择"
            >
              <el-option label="超级管理员" value="超级管理员"> </el-option>
              <el-option label="普通管理员" value="普通管理员"> </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="editDone('ruleForm')" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { userList, delMoreUser, delUser, editUser } from '../../api/users.js'
import { checkName } from '../../utils/validate.js'
import moment from 'moment'
export default {
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: 1,
      dialogVisible: false,
      ruleForm: {
        name: '',
        userGroup: ''
      },
      rules: {
        name: [{ validator: checkName, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data, total } = await userList({
        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
      // console.log(data, total)
      this.tableData = data
      this.total = total
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getUserList()
    },
    // 编辑账号的功能
    edit(obj) {
      this.ruleForm.name = obj.account
      this.ruleForm.userGroup = obj.userGroup
      this.ruleForm.id = obj.id
      this.dialogVisible = true
      console.log(this.ruleForm.name)
    },
    // 修改账号
    editDone(str) {
      this.$refs[str].validate(async valid => {
        if (valid) {
          const { code, msg } = await editUser({
            id: this.ruleForm.id,
            account: this.ruleForm.name,
            userGroup: this.ruleForm.userGroup
          })
          console.log(code, msg)
          if (code === 0) {
            this.$message({
              type: 'success',
              message: msg
            })
            this.getUserList()
          }
          this.dialogVisible = false
        } else {
          this.$message.error('账号不能为空')
          return false
        }
      })
    },
    // 删除账号的功能
    del(id) {
      this.$confirm('此操作将永久删除该账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const data = await delUser({ id })
          this.getUserList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 批量删除账号
    delMore() {
      this.$confirm('此操作将永久删除这些账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const arr = []
          // 多选的每一项
          // console.log(this.multipleSelection)
          for (const item of this.multipleSelection) {
            arr.push(item.id)
          }
          if (!arr.length) return
          const data = await delMoreUser({ ids: JSON.stringify(arr) })
          this.getUserList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  },
  // 重置表单
  watch: {
    dialogVisible(str) {
      if (!this.dialogVisible) {
        this.$refs[str].resetFields()
      }
    }
  },
  // 处理时间
  filters: {
    formateDate(str) {
      return moment(str).format('YYYY-MM-DD HH:mm:ss')
    }
  }
}
</script>

<style lang="less" scoped>
.el-pagination {
  margin: 25px 0px;
}
</style>
